﻿using System;
using System.Activities.Hosting;
using System.Activities.Persistence;
using System.Activities.Tracking;
using System.Collections.Generic;
using System.Xml.Linq;

namespace MvcWebRole1.Workflow
{
    class PromotingTrackingParticipant : TrackingParticipant, IWorkflowInstanceExtension
    {
        public PromotingTrackingParticipant()
        {
            PersistenceParticipant = new PromotingPersistenceParticipant();

            TrackingProfile = new TrackingProfile()
            {
                Queries = 
                { 
                    new ActivityStateQuery()
                    {
                        ActivityName = "*", 
                        States       = {ActivityStates.Closed},
                        Variables    = {"deviceUniqueId", "totalAmount"}
                    }
                }
            };
        }

        private PromotingPersistenceParticipant PersistenceParticipant { get; set; }

        protected override void Track(TrackingRecord record, TimeSpan timeout)
        {
            var stateRecord = record as ActivityStateRecord;
            if (stateRecord != null)
            {
                object value;
                if (stateRecord.Variables.TryGetValue("deviceUniqueId", out value))
                {
                    PersistenceParticipant.DeviceUniqueId = (string)value;
                }
                if (stateRecord.Variables.TryGetValue("totalAmount", out value))
                {
                    PersistenceParticipant.TotalAmount = (decimal)value;
                }
            }
        }


        public IEnumerable<object> GetAdditionalExtensions()
        {
            yield return PersistenceParticipant;
        }

        public void SetInstance(WorkflowInstanceProxy instance)
        {
        }

        class PromotingPersistenceParticipant : PersistenceParticipant
        {
            public string DeviceUniqueId { get; set; }
            public decimal TotalAmount { get; set; }
            protected override void CollectValues(out IDictionary<XName, object> readWriteValues, out IDictionary<XName, object> writeOnlyValues)
            {
                writeOnlyValues = new Dictionary<XName, object>();
                readWriteValues = new Dictionary<XName, object>();
                XNamespace ns = "http://tempuri.org/";
                readWriteValues.Add(ns + "DeviceUniqueId", DeviceUniqueId);
                readWriteValues.Add(ns + "TotalAmount", TotalAmount);
            }
        }
    }
}